// const $isDebug = false;
import Vue from 'vue';
import Router from 'vue-router';
import VueAsyncData from 'vue-async-data';
import VueResource from 'vue-resource';
import lazyLoad from './directive/lazyLoad';

import 'vux/dist/vux.css';

// import * as config from './config';

import filters from './filters/index';

import utils from './factory/utils';
import weixin from './factory/weixin';
import {checkLogin} from './factory/user';
import {setRouter} from './router';

Vue.use(VueResource);
Vue.transition('fade', {
  enterClass: 'fadeIn',
  leaveClass: 'fadeOut'
});
// 告诉 vue “使用” vuex
// 数据请求统一拦截
Vue.http.interceptors.push({
  request: function (request) {
    if (request.url.match(/\.json$/)) {
      request = Object.assign({}, request, {url: request.url + '?t=' + Date.now()});
    }
    return request;
  },
  response: function (response) {
    // let errorMsg = {
    //   401: '未授权',
    //   404: '请求地址不存在',
    //   0: '服务器异常'
    // };
    if (response.status === 200 && ([1].indexOf(response.data.status) > -1) || response.data.errorCode === 200) {
      response.iserror = false;
      return response;
    } else {
      // 511000 将重定向授权
      if (response.request.url.toLowerCase().indexOf('/uc/checkuserinfo') < 0) {
        if (response.status === 401 || [401].indexOf(response.data.status) > -1) {
          // window.location.href = weixin.getWebOAuthUrl();
        } else if (response.status === 200) {
          // window.alertTip(response.data.msg);
          // errorEvent.getResponse(response);
        } else {
          // window.alertTip(errorMsg[response.status]);
          // errorEvent.getResponse(response);
        }
        response.iserror = true;
      }
      // 错误发送
      return response;
    }
  }
});
// 跨站访问的时候，是否使用认证信息(例如cookie或授权的header)
Vue.http.options.xhr = {withCredentials: true};
// 关闭[Vue warn]
Vue.config.warnExpressionErrors = false;

checkLogin().then(res => {
  let info = res.data;
  if (!info.isLogin) {
    window.location.href = weixin.getWebOAuthUrl();
    return;
  }
  window.user = info.user;
  init();
});

function init() {
// use globally
// you can also just use `VueAsyncData.mixin` where needed
  Vue.use(VueAsyncData);
  Vue.use(Router);
  Vue.use(lazyLoad, {
    fadein: true,
    nohori: true,
    speed: 20
  });
// filters
  filters.setFilter(Vue);

  Vue.http.options.emulateJSON = false;
  // {history: true, hashbang: false}
  setRouter(Router);
  window.support.isWEBP = utils.isWEBP();
}

